<template>
  <el-container>
    <el-main>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>卡片名称</span>
          <el-button style="float: right; padding: 3px 0" type="primary" icon="el-icon-plus" size="mini" @click="confirm">确定</el-button>
        </div>
        <el-tree
          ref="tree"
          v-loading="loading"
          :data="menus"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          @check-change="checkChange"
        />
      </el-card>

    </el-main>
  </el-container>
</template>
<script>
import request from '@/utils/request'
import { changeMenuArrayToTree } from '@/utils/menu'
export default {
  name: 'MenuChoose',
  props: {
    keys: {
      type: Array,
      default: () => [],
      require: false
    }
  },
  data: function() {
    return {
      loading: true,
      menus: [],
      defaultProps: {
        label: 'name'
      },
      checkMenuKeys: [],
      checkMenus: []
    }
  },
  watch: {
    keys: {
      immediate: true,
      handler(val) {
        this.loading = true
        this.checkMenuKeys = val
        this.setCheckedKeys()
      }
    }
  },
  created() {
    this.query()
  },
  methods: {
    // menu查询
    query: function() {
      request({
        url: '/system/menu/query',
        method: 'post',
        data: {
          current: 1,
          size: 9999
        }
      }).then(res => {
        const menus = res.data.data
        this.menus = changeMenuArrayToTree(menus)
      })
    },
    checkChange: function(data, checked, indeterminate) {
      // console.log(data, checked, indeterminate)
    },
    // 获取选中的菜单id
    getCheckedKeys: function() {
      this.checkMenuKeys = this.$refs.tree.getCheckedKeys()
    },
    // 获取选中的菜单
    getCheckedNodes() {
      this.checkMenus = this.$refs.tree.getCheckedNodes()
    },
    // 根据Key设置选中的菜单
    setCheckedKeys: function() {
      this.$nextTick(function() {
        this.$refs.tree.setCheckedKeys(this.checkMenuKeys)
        this.loading = false
      })
    },
    confirm: function() {
      this.getCheckedKeys()
      this.getCheckedNodes()
      this.$emit('confirm', this.checkMenuKeys, this.checkMenus)
    }
  }
}
</script>
